<template>
  <div>
    <div v-if="dataList.length == 0">
      <div class="chart-title">
        {{ $t('deviceDetail.diuPage', [timeRange.chartTitle]) }}
      </div>
      <a-empty :image="simpleImage" />
    </div>

    <chart :options="lossoptions" :style="{ height: height + 'px' }" v-else />
    <div v-if="dataList.length == 0">
      <div class="chart-title">
        {{ $t('deviceDetail.delayrat', [timeRange.chartTitle]) }}
      </div>
      <a-empty :image="simpleImage" />
    </div>
    <chart
      :options="delayoptions"
      :style="{ height: height + 'px', marginTop: '20px' }"
      v-else
    />
  </div>
</template>
<script>
import { mapState } from 'vuex';
import { Empty } from 'ant-design-vue';
import { requestHttp, maccApi, fillTimeLineData } from '@utils/index';
import chart from './publicChart.vue';
import moment from 'moment-timezone';
import { i18nRender } from '@/locales';
export default {
  name: 'PingLogsTrend',
  props: {
    deviceInfo: {
      type: Object,
      default: () => {},
    },
    intf: {
      type: String,
      default: '',
    },
    timeRange: {
      type: Object,
      default: () => {
        return {
          end: +new Date(),
          start: +new Date() - 48 * 3600 * 1000,
        };
      },
    },
    height: {
      type: Number,
      default: 250,
    },
  },
  data() {
    return {
      lossoptions: {},
      delayoptions: {},
      dataList: [],
      wanPingConf: null,
    };
  },
  components: {
    chart,
  },
  computed: {
    timezone() {
      const currentGroup =
        this.$store.state.Group.groupMap[this.deviceInfo.groupId];
      return (currentGroup && currentGroup.timezone) || '';
    },
    ...mapState('I18n', ['lang']),
  },
  watch: {
    timeRange: {
      handler() {
        this.init();
      },
      deep: true,
    },
    deviceInfo: {
      handler() {
        this.init();
      },
      deep: true,
    },
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      await this.getWanpingConf();
      await this.getPinglogs();
    },
    async getWanpingConf() {
      const res = await requestHttp({
        api: `${maccApi.GATEWAY_WAN_PINGCONF_GET_API}?sn=${this.deviceInfo.serialNumber}`,
        method: 'GET',
      });
      if (res.code != 0) {
        this.$message.error(res.msg || this.$t('deviceDetail.querywanping'));
        this.wanPingConf = null;
        return;
      }
      console.log(res);
      this.wanPingConf = res;
    },
    async getPinglogs() {
      const { confState, warnState, hosts } = this.wanPingConf;
      if (confState == 'ON' && warnState == 'ON') {
        const res = await requestHttp({
          api: maccApi.GATEWAY_WAN_PINGLOGS_POST_API,
          method: 'POST',
          params: {
            sn: this.deviceInfo.serialNumber,
            host: hosts,
            intf: this.intf,
            startTime: this.timeRange.start,
            endTime: this.timeRange.end,
          },
          module: 'logbiz',
        });
        if (res.code != 0) {
          this.$message.error(res.msg || this.$t('deviceDetail.wanRoad'));
          return;
        }
        let timeList = [];
        let rjlossRateList = [];
        let bdlossRateList = [];
        let rjtimeDelayList = [];
        let bdtimeDelayList = [];

        if (res.map && res.map[hosts[0]] && res.map[hosts[0]].length != 0) {
          this.dataList = res.map[hosts[0]];
          let datalist = res.map[hosts[0]];
          let datamap = res.map[hosts[1]];
          let dataIntervalSeconds, maxMissingIntervalSeconds;
          if (this.timeRange.type == 'hour' || this.timeRange.type == 'day') {
            dataIntervalSeconds = 300;
            maxMissingIntervalSeconds = 3000;
          }
          if (this.timeRange.type == 'week') {
            dataIntervalSeconds = 1800;
            maxMissingIntervalSeconds = 30000;
          }
          if (this.timeRange.type == 'month') {
            dataIntervalSeconds = 2 * 3600;
            maxMissingIntervalSeconds = 1000 * 5 * 60;
          }
          let list, map;
          if (datalist) {
            // list = Array.from(
            //   new Set([
            //     ...,
            //     // ...fillTimeLineData(
            //     //   datalist,
            //     //   datalist[datalist.length - 1].createTime,
            //     //   this.timeRange.end + 1000,
            //     //   'createTime',
            //     //   dataIntervalSeconds,
            //     //   maxMissingIntervalSeconds
            //     // ),
            //   ])
            // );

            list = fillTimeLineData(
              datalist,
              this.timeRange.start,
              this.timeRange.end,
              'createTime',
              dataIntervalSeconds,
              maxMissingIntervalSeconds
            );
          }
          if (datamap) {
            // map = Array.from(
            //   new Set([
            //     ...fillTimeLineData(
            //       datamap,
            //       this.timeRange.start,
            //       this.timeRange.end,
            //       'createTime',
            //       dataIntervalSeconds,
            //       maxMissingIntervalSeconds
            //     ),
            //     // ...fillTimeLineData(
            //     //   datamap,
            //     //   datamap[datamap.length - 1].createTime,
            //     //   this.timeRange.end + 1000,
            //     //   'createTime',
            //     //   dataIntervalSeconds,
            //     //   maxMissingIntervalSeconds
            //     // ),
            //   ])
            // );
            map = fillTimeLineData(
              datamap,
              this.timeRange.start,
              this.timeRange.end,
              'createTime',
              dataIntervalSeconds,
              maxMissingIntervalSeconds
            );
          }

          for (const key in list) {
            timeList.push(list[key].createTime);
            if ('lossRate' in list[key]) {
              rjlossRateList.push(list[key].lossRate);
            } else {
              rjlossRateList.push('-');
            }
            if ('timeDelay' in list[key]) {
              rjtimeDelayList.push(list[key].timeDelay);
            } else {
              rjtimeDelayList.push('-');
            }
          }
          for (const key in map) {
            if ('lossRate' in map[key]) {
              bdlossRateList.push(map[key].lossRate);
            } else {
              bdlossRateList.push('-');
            }
            if ('timeDelay' in map[key]) {
              bdtimeDelayList.push(map[key].timeDelay);
            } else {
              bdtimeDelayList.push('-');
            }
          }

          let losstitle = this.getChartTitle(this.timeRange, 'loss');
          let delaytitle = this.getChartTitle(this.timeRange, 'delay');
          this.lossoptions = this.getLineconfigitems({
            timeList: timeList,
            dataList2: rjlossRateList,
            dataList1: bdlossRateList,
            yname: i18nRender('deviceDetail.discard'),
            xname: i18nRender('deviceDetail.ptime'),
            legend: hosts,
            title: losstitle,
            type: this.getTiemType(this.timeRange.start, this.timeRange.end),
          });
          this.delayoptions = this.getLineconfigitems({
            timeList: timeList,
            dataList2: rjtimeDelayList,
            dataList1: bdtimeDelayList,
            yname: i18nRender('internetuser.delay'),
            xname: i18nRender('deviceDetail.ptime'),
            legend: hosts,
            title: delaytitle,
            type: this.getTiemType(this.timeRange.start, this.timeRange.end),
          });
          (this.lossoptions.yAxis[0].min = 0),
            (this.lossoptions.yAxis[0].max = 100),
            this.lossoptions.series.forEach((ele, index, arr) => {
              arr[index].markLine = {
                data: [
                  {
                    yAxis: 50,
                  },
                ],
                silent: true,
              };
            });
        } else {
          this.lossoptions = {};
          this.delayoptions = {};
        }
      }
    },
    getChartTitle(time, chartType) {
      let scope = time.chartTitle;
      switch (chartType) {
        case 'loss':
          return this.$t('deviceDetail.splitB', [scope]);
        case 'delay':
          return this.$t('deviceDetail.delayD', [scope]);
      }
    },
    getTiemType(start, end) {
      const item = end - start;
      console.log(item);
      const h = 60 * 60 * 1000;
      if (item <= h) {
        return 'minute';
      }
      const day = h * 24;
      if (item <= day * 2) {
        return 'hour';
      }
      const week = day * 7;
      if (item <= week) {
        return 'week';
      }
      return 'month';
    },
    getLineconfigitems(data) {
      let showTick = '';
      let self = this;
      let option = {
        title: {
          text: data.title,
          textStyle: {
            fontSize: 14,
            fontStyle: 'normal',
            fontWeight: 'bolder',
          },
        },
        color: ['#758ffe', '#3ee5fd'],
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
        },
        legend: {
          data: data.legend,
          right: '3%',
          top: '5%',
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            align: 'left',
            color: 'rgba(255,255,255,1)',
          },
          backgroundColor: 'rgba(0,0,0,0.5)', //设置背景图片 rgba格式
          borderWidth: 0,
          padding: 5,
          formatter: (params) => {
            let res = '';
            let restop = '';
            for (let i = 0; i < params.length; i++) {
              const timeString = moment(Number(params[i].axisValue))
                .tz(this.timezone)
                .format('YYYY/MM/DD HH:mm:ss');
              restop = '<span>' + timeString + '</span><br/>';
              res +=
                '<span>' +
                params[i].marker +
                params[i].seriesName +
                ' : ' +
                params[i].data +
                '</span><br/>';
            }
            return restop + res;
          },
          axisPointer: {
            type: 'shadow',
            animation: false,
            label: {
              backgroundColor: '#505765',
            },
          },
        },
        xAxis: {
          name: data.type == 'hour' ? data.xname : '',
          type: 'category',
          boundaryGap: false,
          axisLine: {
            onZero: false,
          },
          axisTick: {
            show: true,
          },
          axisLabel: {
            formatter: (value) => {
              let str;
              switch (data.type) {
                case 'minute':
                  str = moment(Number(value)).tz(self.timezone).format('HH:mm');
                  break;
                case 'hour':
                  str = moment(Number(value)).tz(self.timezone).format('H');
                  break;
                case 'day':
                  str = moment(Number(value)).tz(self.timezone).format('H');
                  break;
                case 'week':
                  if (self.lang == 'zh') {
                    const timeString = moment(Number(value))
                      .tz(self.timezone)
                      .format('YYYY/MM/DD HH:mm:ss');
                    str = new Date(timeString).Format('W');
                  } else {
                    str = moment(Number(value)).tz(self.timezone).format('ddd');
                    console.log(moment(Number(value)).tz(self.timezone), str);
                  }

                  break;
                case 'month':
                  str = moment(Number(value)).tz(self.timezone).format('DD');
                  break;
              }
              return str;
            },
          },
          data: data.timeList,
        },
        yAxis: [
          {
            name: data.yname,
            type: 'value',
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: data.legend[0],
            type: 'line',
            smooth: true,
            areaStyle: {},
            lineStyle: {
              width: 1,
            },
            data: data.dataList2,
          },
          {
            name: data.legend[1],
            type: 'line',
            smooth: true,
            areaStyle: {},
            lineStyle: {
              width: 1,
            },
            data: data.dataList1,
          },
        ],
      };
      option.xAxis.axisLabel.interval = function (index, value) {
        let show = false;
        switch (data.type) {
          case 'hour': {
            if (data.title.indexOf(i18nRender('deviceDetail.oTime')) != -1) {
              show = true;
            } else {
              let str = new Date(Number(value)).Format('h');
              if (showTick != str && parseInt(str) % 2 == 0) {
                showTick = str;
                show = true;
              }
            }
            break;
          }
          case 'day': {
            let str = new Date(Number(value)).Format('h');
            if (showTick != str && parseInt(str) % 2 == 0) {
              showTick = str;
              show = true;
            }
            break;
          }
          case 'week': {
            let str = moment(Number(value)).tz(self.timezone).format('ddd');
            if (showTick !== str) {
              showTick = str;
              show = true;
            }
            break;
          }
          case 'month': {
            let str = new Date(Number(value)).Format('D');
            if (showTick !== str) {
              showTick = str;
              show = true;
            }
            break;
          }
        }
        return show;
      };
      return option;
    },
  },
};
</script>
<style lang="less" scoped>
.chart-title {
  font-size: 14px;
  font-weight: bolder;
  margin-top: 12px;
}
</style>
